package com.igeek.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 字符编码的过滤
 */
@WebFilter("/*")
public class EncodingFilter implements Filter {
    /**
     * 过滤器的初始化方法只执行一次
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 过滤业务处理的方法
     * @param request
     * @param response
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        //只针对post
        //request.setCharacterEncoding(encode);
        HttpServletRequest req=(HttpServletRequest)request;
        HttpServletResponse res=(HttpServletResponse)response;
        //创建自定义的请求类
        MyRquest myRquest=new MyRquest(req);
        res.setContentType("text/html;charset=utf-8");
        //如果该过滤器只是起到增强的作用,那么执行完该过滤器之后还需要继续展示相应的页面
        filterChain.doFilter(myRquest,res);
    }

    @Override
    public void destroy() {

    }
}
